<?php

class Articles extends CI_Controller {

    public function __construct()
	{
		parent::__construct();
		//check session
		$this->session->set_userdata(array('redirectUrl' =>current_url()));
		check_user_login();
		$this->load->model('Blog_model', 'blog');
	}

	//the home page of the blog
	public function index()
	{
		$entries['title'] = 'Informations & Market Review Articles';
		$entries['query'] = $this->blog->get_all_entries();
		$this->load->view('articles/index', $entries);
	}

	//For an individual entry, the url title is used to grab 
	//the entry
	public function entry($url_title = "")
	{
		
		  if($url_title){
			
			$entry_data['post'] = $this->blog->get_entry($url_title);
			
			if(!$entry_data['post']){
			  redirect('/articles', 'location');
			} else {
			  $this->load->view('articles/entry', $entry_data);
			}
		 } else {
		   redirect('/articles', 'location');
		 }
	}
	//post an article
	public function post()
	{
		//check session
		$this->session->set_userdata(array('redirectUrl' =>current_url()));
		check_user_login();
		$data['title'] = "Post an article";
		$data['action'] = '/admin/articles/add';
		$data['categories'] = $this->blog->get_category();
		$this->load->view('admin/articles/form', $data);
	}
	public function add()
	{
		//check session
		$this->session->set_userdata(array('redirectUrl' =>current_url()));
		check_user_login();
		if ($this->form_validation->run('articlefrm') == FALSE){
			$this->post();
		}else{
			// save data
			$article = array('title' => $this->input->post('articletitle'),
					'summary' =>$this->input->post('articlesummary'),
					'entry' => $this->input->post('entry'),
					'authorID' => (int) $this->session->userdata('userid'),
					'url_title'=> str_replace(' ', '_', $this->input->post('articletitle'))
					);

			if (isset($_FILES['userfile']['tmp_name']) && !empty($_FILES['userfile']['tmp_name'])) {
				$image_url = upload_file('','','/articles');
				if($image_url){
					$urls = array_values($image_url);
					$article['image_url'] = isset($urls[0]) ? $urls[0] : null;;
					}else{
						$data = array('message' => $this->upload->display_errors(), 'action' => 'admin/article/add');
						$this->load->view('admin/articles/form', $data);
					}
			}
			//$article['year'] = date('Y');
			//$article['month'] = date('M');

			if ($this->input->post('catg')){
				$article['categoryID'] = $this->input->post('catg');
			}
			$this->load->model('Blog_model','',TRUE);
			$result = $this->Blog_model->save($article);
			redirect('/articles', 'location');
		}
		
	}

}

/* End of file articles.php */
/* Location: ./controllers/admin/articles.php */ 

?>
